//工具函数
//图片导出为 png 格式
var type = 'png';
// var imgData = canvas.toDataURL(type);

/**
 * 获取mimeType
 * @param  {String} type the old mime-type
 * @return the new mime-type
*/
var _fixType = function (type) {
  type = type.toLowerCase().replace(/jpg/i, 'jpeg');
  var r = type.match(/png|jpeg|bmp|gif/)[0];
  return 'image/' + r;
};

// 加工image data，替换mime type
//imgData = imgData.replace(_fixType(type),'image/octet-stream');

/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
var downCanvasImg = function (dataO, filename = "乱码_赛博朋克2077VG百科") {
  let data = dataO
  // // console.log(dataO)
  // if(typeof dataO == "string"){
  //   data = dataO
  // }else{
  //   data  = dataO.toDataURL("image/png");
  // }

  filename = filename //||randomName(filename)
  // window.open(data)
  //window.open(URL.createObjectURL(dataURL2blob(data)));
  if('msSaveOrOpenBlob' in navigator){
    window.navigator.msSaveOrOpenBlob(data, filename+".png");
    return;
  }
  downloadImg(data,filename+".png")
  return
  var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  save_link.href = URL.createObjectURL(dataURL2blob(data));

  save_link.download = filename + ".png";
  var event = document.createEvent('MouseEvents');
  event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  save_link.dispatchEvent(event);
};


function randomName(name) {
  return new Date().getTime() + name;
}


function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

/**
 * dataURL 转成 blob 兼容版
 * @param dataURL
 * @return blob
 */
function dataURL2blob(dataURL) {
  let binaryString = atob(dataURL.split(',')[1]);
  let arrayBuffer = new ArrayBuffer(binaryString.length);
  let intArray = new Uint8Array(arrayBuffer);
  let mime = dataURL.split(',')[0].match(/:(.*?);/)[1]
  for (let i = 0, j = binaryString.length; i < j; i++) {
    intArray[i] = binaryString.charCodeAt(i);
  }
  let data = [intArray];
  let result;
  try {
    result = new Blob(data, { type: mime });
  } catch (error) {
    window.BlobBuilder = window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MozBlobBuilder ||
          window.MSBlobBuilder;
    if (error.name === 'TypeError' && window.BlobBuilder) {
      var builder = new BlobBuilder();
      builder.append(arrayBuffer);
      result = builder.getBlob(type);
    }else if(e.name == "InvalidStateError"){
      result =  new Blob( [intArray.buffer], {type : mime});
    } else {
      alert("没救了")
      throw new Error('没救了');
    }
  }
  return result;
}
// function exportCanvasAsPNG(imgURL, filename = "") {
//   var MIME_TYPE = "image/png";
//   var imgURL = imgURL;
//   filename = randomName(filename);
//   //IE下
//   if('msSaveOrOpenBlob' in navigator){
//     window.navigator.msSaveOrOpenBlob(dataURLtoBlob(imgURL), filename+".png");
//     return;
//   }
//   var dlLink = document.createElement('a');
//   dlLink.download = filename + ".png";
//   dlLink.href = URL.createObjectURL(dataURLtoBlob(imgURL));;
//   dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
//   document.body.appendChild(dlLink);
//   dlLink.click();
//   document.body.removeChild(dlLink);
// }

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
function debounce(func,wait,immediate) {
  let timeout;

  return function () {
    let context = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    }
    else {
      timeout = setTimeout(function(){
        func.apply(context, args)
      }, wait);
    }
  }
}
/**
 * @desc 通过base64改变图片大小
 * @param {参数obj} param 
* @param {输出图片宽度} param.width 不传初始赋值-1，等比缩放不用传高度
 * @param fnc 回调
 */
function imgChangeToBase(param,fnc=function(){}){
  if(!param||!param.base64){
    return
  }
  var image = new Image();
  image.src = param.base64;
  image.onload = function(){
    var scale = this.width / this.height;
    // console.log(scale);
    //创建一个canvas
    var canvas = document.createElement('canvas');
    //获取上下文
    var context = canvas.getContext('2d');
    //获取压缩后的图片宽度,如果width为-1，默认原图宽度
    canvas.width = param.width;
    //获取压缩后的图片高度,如果width为-1，默认原图高度
    canvas.height = param.height || parseInt(param.width / scale);
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    //压缩图片，获取到新的base64Url
    var newImageData = canvas.toDataURL("image/png");
    //debugger
    fnc(newImageData)
    canvas=null;
  }
}

function downloadImg(src,name){
  // 获取图片地址
  var a = document.createElement('a');          // 创建一个a节点插入的document
  var event = new MouseEvent('click')           // 模拟鼠标click点击事件
  a.download = name                            // 设置a节点的download属性值
  a.href = src;                                 // 将图片的src赋值给a节点的href
  a.dispatchEvent(event)                        // 触发鼠标点击事件
}

function isMobile() {
  const userAgentInfo = navigator.userAgent
  const Agents = [
    'Android',
    'iPhone',
    'iPad',
    'iPod'
  ]
  let flag = false
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = true
      break
    }
  }
  return flag
}

//对图片旋转处理 
function rotateImg(img, direction=0) { 
  var expectWidth = img.naturalWidth;
  var expectHeight = img.naturalHeight;
  var canvas = document.createElement("canvas")
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, expectWidth, expectHeight);
  //alert(img);
  //最小与最大旋转方向，图片旋转4次后回到原方向 

  //var img = document.getElementById(pid); 
  if (img == null)return; 
  //img的高度和宽度不能在img元素隐藏后获取，否则会出错 
  var height = img.height; 
  var width = img.width; 


  //旋转角度以弧度值为参数 
  var degree = direction * Math.PI / 180; 
  ctx = canvas.getContext('2d'); 
  switch (direction) { 
  case 0: 
    canvas.width = width; 
    canvas.height = height; 
    ctx.drawImage(img, 0, 0); 
    break; 
  case 90: 
    canvas.width = height; 
    canvas.height = width; 
    ctx.rotate(degree); 
    ctx.drawImage(img, 0, -height); 
    break; 
  case 180: 
    canvas.width = width; 
    canvas.height = height; 
    ctx.rotate(degree); 
    ctx.drawImage(img, -width, -height); 
    break; 
  case 270: 
    canvas.width = height; 
    canvas.height = width; 
    ctx.rotate(degree); 
    ctx.drawImage(img, -width, 0); 
    break; 
  }
  let base64 = canvas.toDataURL("image/png", 1)
  canvas=null
  return base64
} 


export { downCanvasImg,debounce,imgChangeToBase,rotateImg,isMobile,dataURL2blob } 